numCourses = 4
prerequisites = [[1,0],[2,0],[3,1],[3,2]]
def findOrder(numCourses: int, prerequisites):
    #创建一个字典来存放课程的前置课程数量
    dictionary=dict()
    #初始化字典
    for i in range(numCourses):
        dictionary[i]=0
    #统计前置课程数量
    for prerequisite in prerequisites:
        dictionary[prerequisite[0]]+=1

    #做一个集合用来存放没有前置课程的课
    courseSet=set()
    ans=[]   #这里额外做一个存放结果的数组
    for key in dictionary.keys():
        if dictionary[key]==0:
            courseSet.add(key)
            ans.append(key)
    flag=True
    while flag and len(prerequisites)>0:
        flag=False
        prerequisitesLen=len(prerequisites)
        while prerequisitesLen>0:
            #队首元素弹出
            prerequisite=prerequisites.pop(0)
            if prerequisite[1] in courseSet:
                #前置课程在集合里面
                dictionary[prerequisite[0]]-=1
                if dictionary[prerequisite[0]]<=0:
                    flag=True
                    courseSet.add(prerequisite[0])
                    ans.append(prerequisite[0])
            else:
                #不在集合里面，就把这个值再放回去
                prerequisites.append(prerequisite)
            prerequisitesLen-=1
    if len(ans)<numCourses:
        return []
    else:
        return ans
print(findOrder(numCourses,prerequisites))




